//
//  Model.m
//  SimpleSearch
//
//  Created by Ryan on Tue Nov 11 2003. 
//
//  ****************
//  Short Disclaimer (please read!):
//
//  Why open source?  This project was briefly popular several years ago and has since lost interest (on both
//  my part and the public's part).  Rather than letting it moulder for eternity, I decided to open source it 
//  in case anyone else is interested in renovating it and bringing it up to date.
//
//  My main concern with open sourcing it is that this program is one of the first Cocoa programs I wrote and
//  as such, it is in no way representative of my current coding style!  Many things are done incorrectly in 
//  this code base but I have not taken the time to revise them for the open source release. Hence, if you work
//  for a company looking to hire me, don't look too critically at this old code!
//
//  This code was originally written in 2002 to 2003 and hence was created before technologies such as 
//  Cocoa Bindings and properties (Obj-C 2.0) existed.  Much of the code could be ripped out and replaced 
//  with the newer way of doing things.
//
//  The GUI is also fairly out of date and in need of some serious updating.
//  
//  Have fun!
//  April, 2008.
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.


#import "Model.h"
#import "Plugin.h"

@interface Model ()

- (void)verifyExistenceOfPluginDirectory;

@end


@implementation Model

- (id)init {
	if (self = [super init]) {
		plugins = [[NSMutableDictionary dictionary] retain];
		
		[self verifyExistenceOfPluginDirectory];
		[self readPlugins];

	}
	return self;
}



// Make sure the plugin directory is in the right place.  If it
// doesn't already exist, then copy a couple of default plugins from
// the application bundle into this directory.
- (void)verifyExistenceOfPluginDirectory {
	BOOL alreadyExists = NO;
	BOOL b;
	
	NSFileManager * fm = [NSFileManager defaultManager];
	NSString * path;
	
	// First we'll check to see if "Simple Search" exists in the
	// "~/Library/Application Support" directory.
	
	path = [NSString stringWithString:@"~/Library/Application Support/Simple Search"];
	path = [path stringByExpandingTildeInPath];
	b = [fm fileExistsAtPath:path];
	
	if (!b) {  // Then create it
		b = [fm createDirectoryAtPath:path attributes: nil];
	}
	
	path = [NSString stringWithString:@"~/Library/Application Support/Simple Search/Plugins"];
	path = [path stringByExpandingTildeInPath];	
	b = [fm fileExistsAtPath:path];
	
	alreadyExists = b;
	
	if (!b) {  // Then create it
		b = [fm createDirectoryAtPath:path attributes: nil];		
	}
	
	// So, at this point, we should have the proper directory structure set up...

	// If the directory doesn't exist OR if the user hasn't ever launched 
	// Simple Search before (ie, if they are upgrading from an older version which
	// used the old style plugins, then we should copy the default plugins over.
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	if (!alreadyExists || (![defaults boolForKey:@"Valid Prefs"])) {

//*******************		
		path = [NSString stringWithString:@"~/Library/Application Support/Simple Search/Plugins/google.xml"];
		path = [path stringByExpandingTildeInPath];	
		
		NSBundle * bund = [NSBundle mainBundle];
		NSString * appPath = [NSString stringWithFormat: 
			@"%@/Contents/Resources/google.xml", [bund bundlePath]];
		
		b = [fm copyPath: appPath
			toPath: path
			handler: nil];
		
//*******************		
		path = [NSString stringWithString:@"~/Library/Application Support/Simple Search/Plugins/dictionary.xml"];
		path = [path stringByExpandingTildeInPath];	
		
		appPath = [NSString stringWithFormat: 
			@"%@/Contents/Resources/dictionary.xml", [bund bundlePath]];
		
		//NSLog(@"AppPath = %@", appPath);
		
		b = [fm copyPath: appPath
					 toPath: path
					handler: nil];
//*******************		

		path = [NSString stringWithString:@"~/Library/Application Support/Simple Search/Plugins/run program.xml"];
		path = [path stringByExpandingTildeInPath];	
		
		appPath = [NSString stringWithFormat: 
			@"%@/Contents/Resources/run program.xml", [bund bundlePath]];
		
		//NSLog(@"AppPath = %@", appPath);
		
		b = [fm copyPath: appPath
						   toPath: path
						  handler: nil];
//*******************		
		path = [NSString stringWithString:@"~/Library/Application Support/Simple Search/Plugins/show url.xml"];
		path = [path stringByExpandingTildeInPath];	
		
		appPath = [NSString stringWithFormat: 
			@"%@/Contents/Resources/show url.xml", [bund bundlePath]];
		
		//NSLog(@"AppPath = %@", appPath);
		
		b = [fm copyPath: appPath
						   toPath: path
						  handler: nil];
//*******************		
		
	}	
}


// Read the user's plugins which should be located in the 
// ~/Library/Application Support/Simple Search/Plugins folder, or the same path at the global /Library folder.
- (void)readPlugins {
/*
	NSString * path = [NSString stringWithFormat: 
		@"%@/Library/Application Support/Simple Search/Plugins/newpluginformat.xml",
		NSHomeDirectory()];
*/	
	
	NSString * path = [NSString stringWithFormat: 
		@"%@/Library/Application Support/Simple Search/Plugins/", NSHomeDirectory()];
	
	NSFileManager * fm = [NSFileManager defaultManager];
	
	// Get a list of all the files in the plugins directory.
	NSArray * dirList = [fm directoryContentsAtPath: path];
	
	Plugin * p;

	// Loop through all the files in the directory.
	NSEnumerator *enumerator = [dirList objectEnumerator];
	id anObject;
	
	while (anObject = [enumerator nextObject]) {
		p = [[Plugin alloc] initWithPath: 
			[NSString stringWithFormat: @"%@%@", path, (NSString *)anObject]];
			
		if (p != nil) {
			[plugins setObject:p forKey:[p name]];
			[p release];
		}
	}


	// Now, we should check in the global Application Support folder to see if they
	// have installed any global plugins.  Local plugins take precedence over globals,
	// so if a local and a global exist with the same name, use the local.

	path = [NSString stringWithFormat:@"/Library/Application Support/Simple Search/Plugins/"];
	if ([fm fileExistsAtPath:path]) {	// Only bother if the global directory already exists.
										
		// Get a list of all the files in the plugins directory.
		dirList = [fm directoryContentsAtPath: path];
		
		// Loop through all the files in the directory.
		enumerator = [dirList objectEnumerator];
		
		while (anObject = [enumerator nextObject]) {
			p = [[Plugin alloc] initWithPath: 
				[NSString stringWithFormat: @"%@%@", path, (NSString *)anObject]];
			
			if (p != nil) {
				if ([plugins objectForKey:[p name]] == nil ) {
					// If a plugin of that name doesn't already exist, then
					// add it to the dictionary.
					[plugins setObject:p forKey:[p name]];
				}
				[p release];
			}
		}			
	}

}


- (int)numPlugins {
	return [plugins count];
}


- (NSArray*)pluginNames {
	return [plugins allKeys];
}

- (Plugin *)pluginNamed: (NSString *)name {
	return [plugins objectForKey: name];
}


- (void)showWebSiteWithPluginName: (NSString *)name optionIndex: (int)oIndex query: (NSString*)q {
	if (nil == plugins) {
		NSLog(@"plugins is nil");
	}
	
//	NSLog(@"num plugins = %d", [self numPlugins]);

	Plugin * p = [[plugins objectForKey: name] retain];
	if (p) {
		[p showWebSiteWithOptionIndex: oIndex query:q];

		[p release];
	}
}

- (void)dealloc {

	[plugins release];
	[super dealloc];	
}

@end
